package com.neu.api.Interceptor;

import com.neu.api.properties.JWTProperties;
import com.neu.api.utils.JSONUtil;
import com.neu.api.utils.JWTUtil;
import com.neu.api.utils.Result;
import com.neu.api.utils.StringUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Resource
    JWTProperties jwtProperties;
    //拦截器
    //固定代码
    //步骤：一个类创建 HandlerInterceptor，实现方法请求，之后配置


    //进入控制器之前调用这个方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        if(request.getMethod().equals(RequestMethod.OPTIONS.name())){
            return true;
        }

        System.out.println("拦截了："+request.getRequestURI());


        //怎么判断当前请求是否已登录了呢？
        //从请求头中获取token,然后判断是否有效
        //token都没有
        //token有
        //判断token的合法性

        String token = request.getHeader("token");

        if(StringUtil.isEmpty(token)){
            //请求头中没有token
            response.setContentType("application/json;charset=utf-8");
            PrintWriter printWriter =  response.getWriter();
            printWriter.print(JSONUtil.objToJson(Result.failure("你还没登录，请重新登录")));
            return false;
        }else {
            //判断token的合法性
            try{
                JWTUtil.parseJWT(token,jwtProperties.getSecure());
                return true;
            }catch (Exception e){
                //说明token不合法
                //请求头中没有token
                response.setContentType("application/json;charset=utf-8");
                PrintWriter printWriter =  response.getWriter();
                printWriter.print(JSONUtil.objToJson(Result.failure("token不合法 或 token已过期，请重新登录！")));
                return false;
            }
        }
    }
}
